package com.sct.platform;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button mResetServer;
    Button mKillServer;
    Button mStartServer;
    Button mRestartServer;
    String mBasePath;
    TextView mStatus;

    private String byte2String(byte[] buf, int sz)
    {
        byte[] b0 = new byte[sz];
        System.arraycopy(buf, 0, b0, 0, sz);
        return new String(b0);
    }

    private int systemCall(String[] command)
    {
        return systemCall(command, false);
    }

    private int systemCall(String[] command, boolean needLog)
    {
        ProcessBuilder builder = new ProcessBuilder(command);


        Process proc = null;
        try {
            proc = builder.start();
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }

        byte[] buf = new byte[100];
        int sz = 0;

        boolean shouldExit = false;
        int ret = 0;
        while(true)
        {

            if(needLog) {
                try {
                    InputStreamReader isr = new InputStreamReader(proc.getInputStream());
                    BufferedReader br = new BufferedReader(isr);

                    while (true) {
                        if (br.ready()) {
                            System.out.println(br.readLine());
                        } else {
                            break;
                        }
                    }

                    isr = new InputStreamReader(proc.getErrorStream());
                    br = new BufferedReader(isr);

                    while (true) {
                        if (br.ready()) {
                            System.out.println(br.readLine());
                        } else {
                            break;
                        }
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(shouldExit)
            {
                return ret;
            }

            try {
                ret = proc.exitValue();
                shouldExit = true;
            } catch (IllegalThreadStateException e)
            {
                try {
                    Thread.sleep(50, 0);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                continue;
            }
        }

    }


    private int createFile(String fileDirPath,String fileName,int id) {
        String filePath = fileDirPath + "/" + fileName;// 文件路径
        try {
            File dir = new File(fileDirPath);// 目录路径
            if (!dir.exists()) {// 如果不存在，则创建路径名
                dir.mkdirs();
            }
            // 目录存在，则将apk中raw文件夹中的需要的文档复制到该目录下
            File file = new File(filePath);
            if (!file.exists()) {// 文件不存在
                InputStream is = getResources().openRawResource(
                        id);// 通过raw得到数据资源
                FileOutputStream fs = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int count = 0;// 循环写出
                while ((count = is.read(buffer)) > 0) {
                    fs.write(buffer, 0, count);
                }
                fs.close();// 关闭流
                return 1;
            }
            else
            {
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        mResetServer = (Button) findViewById(R.id.resetserver);
        mKillServer = (Button) findViewById(R.id.killserver);
        mStartServer = (Button) findViewById(R.id.startserver);
        mRestartServer = (Button) findViewById(R.id.restartserver);
        mStatus = (TextView) findViewById(R.id.status);

        mResetServer.setOnClickListener(this);
        mKillServer.setOnClickListener(this);
        mStartServer.setOnClickListener(this);
        mRestartServer.setOnClickListener(this);


        int ret = 0;
        String basePath = "/data/data/" + getApplicationContext().getPackageName();
        mBasePath = basePath;

        ///////////////////////////setup programs//////////////////////////////////
        ///setup busybox
        File file = new File(basePath + "/busybox");
        if(!file.exists())
        {
            createFile(basePath, "busybox", R.raw.busybox);
            systemCall(new String[]{"chmod", "777", basePath + "/busybox"});
            systemCall(new String[]{basePath + "/busybox"}, true);
        }

        ///setup python
        File dir = new File(basePath +"/python-android-install");
        if(!dir.exists())
        {
            createFile(basePath, "python.tar", R.raw.python);

            Log.v("sct", "decompressing python...");
            ret = systemCall(new String[]{basePath + "/busybox", "tar", "-C", basePath,  "-xf", basePath + "/python.tar"});
            Log.v("sct", "finished");

            systemCall(new String[]{"chmod", "-R", "777", basePath + "/python-android-install"});
            systemCall(new String[]{basePath + "/python-android-install/bin/python", "-V"}, true);
        }

        ///setup broadcastserver
        createFile(basePath, "testbroadcastclient.py", R.raw.testbroadcastclient);
        createFile(basePath, "testbroadcastserver.py", R.raw.testbroadcastserver);

        ///setup nginx
        dir = new File(basePath + "/nginx-android-install");
        if(!dir.exists())
        {
            createFile(basePath, "nginx.tar", R.raw.nginx);

            Log.v("sct", "decompressing nginx...");
            systemCall(new String[]{basePath + "/busybox", "tar", "-C", basePath, "-xf", basePath + "/nginx.tar"});
            Log.v("sct", "finished");

            systemCall(new String[]{"chmod", "-R", "777", basePath + "/nginx-android-install"});
            systemCall(new String[]{basePath + "/nginx-android-install/sbin/nginx", "-v"}, true);
        }

        ///setup servermanager
        createFile(basePath, "testservermanager.py", R.raw.testservermanager);

        ///setup web.py
        createFile(basePath, "testweb.py", R.raw.testweb);

        ///setup libs
        dir = new File(basePath + "/lib-android-install");
        if(!dir.exists())
        {
            createFile(basePath, "libinstall.tar", R.raw.libinstall);

            Log.v("sct", "decompressing lib-android-install ...");
            systemCall(new String[]{basePath + "/busybox", "tar", "-C", basePath, "-xf", basePath + "/libinstall.tar"});
            Log.v("sct", "finished");

            systemCall(new String[]{"chmod", "-R", "777", basePath + "/lib-android-install"});
        }

        ///setup testmicrohttpd
        file = new File(basePath + "/testmicrohttpd");
        if(!file.exists())
        {
            createFile(basePath, "testmicrohttpd", R.raw.testmicrohttpd);

            systemCall(new String[]{"chmod", "-R", "777", basePath + "/testmicrohttpd"});
        }

        ///setup spawn-fcgi
        dir = new File(basePath + "/spawn-fcgi-android-install");
        if(!dir.exists())
        {
            createFile(basePath, "spawn.tar", R.raw.spawn);

            Log.v("sct", "decompressing spawn-fcgi-android-isntall ...");
            systemCall(new String[]{basePath + "/busybox", "tar", "-C", basePath, "-xf", basePath + "/spawn.tar"});
            Log.v("sct", "finished");

            systemCall(new String[]{"chmod", "-R", "777", basePath + "/spawn-fcgi-android-install"});
        }

        ///setup testfcgi.py
        file = new File(basePath + "/testfcgi.py");
        if(!file.exists())
        {
            createFile(basePath, "testfcgi.py", R.raw.testfcgi);

            systemCall(new String[]{"chmod", "-R", "777", basePath + "/testfcgi.py"});
        }

        ////////////////////////////////run server//////////////////////////////////////////////////
        Log.v("sct", "start server");
        ret = systemCall(new String[]{basePath + "/python-android-install/bin/python", basePath + "/testservermanager.py", "reset"}, true);
        Log.v("sct", "ret:" + ret);
//
//        Log.v("sct", "start server");
//        ret = systemCall(new String[]{basePath + "/python-android-install/bin/python", basePath + "/testbroadcastserver.py"});
//        Log.v("sct", "ret:" + ret);
//
//        File file = new File(basePath + "/nginxdir/logs/nginx.pid");
//        if(!file.exists()) {
//            Log.v("sct", "start nginx server");
//            ret = systemCall(new String[]{basePath + "/nginxdir/sbin/nginx", "-p", basePath + "/nginxdir"}, true);
//            Log.v("sct", "ret:" + ret);
//        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        String basePath = mBasePath;

        switch (v.getId())
        {
            case R.id.startserver:
            {
                mStatus.setText("start server ...");
                systemCall(new String[]{basePath + "/python-android-install/bin/python", basePath + "/testservermanager.py", "start"}, true);
                mStatus.setText("start server end. server running");
                break;
            }

            case R.id.killserver:
            {
                mStatus.setText("try to kill server");
                systemCall(new String[]{basePath + "/python-android-install/bin/python", basePath + "/testservermanager.py", "kill"}, true);
                mStatus.setText("kill server finished");
                break;
            }

            case R.id.restartserver:
            {
                mStatus.setText("try to restart server");
                systemCall(new String[]{basePath + "/python-android-install/bin/python", basePath + "/testservermanager.py", "restart"}, true);
                mStatus.setText("restart end. server running");
                break;
            }

            case R.id.resetserver:
            {
                mStatus.setText("try to reset server");
                systemCall(new String[]{basePath + "/python-android-install/bin/python", basePath + "/testservermanager.py", "reset"}, true);
                mStatus.setText("reset end. server running");
                break;
            }

            default:
            {
                Log.v("sct", "error happen");
                break;
            }
        }
    }
}
